<!--
 * @Author: tenet 18742176629@163.com
 * @Date: 2024-05-22 20:22:04
 * @LastEditors: toString muzi_li0323@163.com
 * @LastEditTime: 2024-05-23 23:38:49
 * @FilePath: /chain-link-api-front/src/views/currencyManagement/index.vue
 * @Description: 币种管理
-->
<template>
  <!-- 添加币种 dialog -->
  <el-dialog class="addCurrency" v-model="dialogVisible" :modal="false" append-to-body @close="handleClose"
             @open="resetSelectToFirst"
             width="450" style="height: 600px;margin-left: 320px; margin-top:198px;border-radius:10px"
             max-hight="600px">
    <div class="addHeader">
      <el-select v-model="ruleForm.chainId" filterable @change="getAllTokenListFun"
                 :placeholder="$t('global.PleaseSelect') + t('table.ChainName')" style="width: 70%;">
        <el-option v-for="(item, index) in canAddList" :key="index" :label="item.chainName" :value="item.chainId"/>
      </el-select>
      <el-input v-model.trim="symbol" :placeholder="$t('global.PleaseInput') + $t('table.Symbol')"
                @input="handleSymbol()"/>

<!--      <el-select v-model="ruleForm.symbol" filterable @change="getAllTokenListFun"-->
<!--                 :placeholder="$t('global.PleaseInput') + t('table.Symbol')" style="width: 70%;">-->
<!--        <el-option v-for="(item, index) in tokenList" :key="index" :label="item.symbol" :value="item.symbol"/>-->
<!--      </el-select>-->

    </div>

    <div class="addBody scrollable-container" style="height: 420px; max-height: 420px; overflow-y:auto; overflow-x: hidden ">
      <div class="body_content" v-for="(item, index) in tokenList" :key="index" v-show="item.isShow">
        <div class="body_left" >
          <el-checkbox :value="item.id" :indeterminate="false" :checked="checkList.includes(item.id)" @change="handleCheck(item.id, $event)">
            <div class="body_right">
              <div class="currencyName"> {{ item.symbol }}</div>
              <div>{{ item.address }}</div>
            </div>
          </el-checkbox>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer"
           style="display: flex; flex-direction: row; justify-content: space-between; align-items: center">
<!--        <el-tooltip-->
<!--            class="box-item"-->
<!--            effect="dark"-->
<!--            :content="t('message.AddCurrencyTips1')"-->
<!--            placement="top-start"-->
<!--        >-->
          <el-button type="primary" @click="submit">{{ $t('global.ConfirmAdd') }}</el-button>
<!--        </el-tooltip>-->
      </div>
    </template>
  </el-dialog>

  <Header>
    <template #title>{{ $t('title.CurrencyManagement') }}</template>
  </Header>
  <div class="container">
    <!-- 查询 -->
    <div class="searchBar">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item :label="$t('table.Address2')">
          <el-input v-model.trim="queryParams.address" :placeholder="$t('global.PleaseInput') + $t('table.Address2')"
                    clearable/>
        </el-form-item>
        <el-form-item :label="$t('table.Symbol')">
          <el-input v-model.trim="queryParams.symbol" :placeholder="$t('global.PleaseInput') + $t('table.Symbol')"
                    clearable/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" round @click="onSubmit(queryParams.address, queryParams.symbol)">
            {{ $t('button.Search') }}
          </el-button>
          <el-button type="default" :icon="Refresh" round plain @click="onReset()">{{ $t('button.Reset') }}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="btn">
      <el-button type="primary" round @click="funAdd">{{ $t('currencyManagement.AddCurrency') }}</el-button>
    </div>
    <el-table :data="invoiceData.tableData" border style="width: 100%; height: 600px" v-loading="loading"
              size="large">
      <el-table-column prop="mainCoinType" :label="$t('table.ChainIdMainCoinType')" width="300"
                       align="center"></el-table-column>
      <el-table-column prop="symbol" :label="$t('table.Symbol2')" width="auto" align="center"></el-table-column>
      <el-table-column prop="address" :label="$t('table.AddressCoinType')" width="auto"
                       align="center"></el-table-column>
    </el-table>

    <div class="page">
      <el-pagination v-model:current-page="pageIndex" :page-size="pageSize" layout="total, prev, pager, next"
                     :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
    </div>
  </div>
</template>
<script setup>
import {reactive, ref, unref, onMounted, computed} from 'vue'
import {ElTable, ElMessage, ElPagination} from 'element-plus'
import {Search, Refresh} from '@element-plus/icons-vue'
import Header from '../layout/header.vue'
import {getConfigList, getAllTokenList, getUserTokens, addToken} from '@/require/api.js'
import {useI18n} from "vue-i18n";
const {t} = useI18n();

// 在组件被挂载后执行
onMounted(() => {
  getChainList()
  getList()
});


const pageSize = ref(10)
const pageIndex = ref(1)
const canAddList = ref([]) // 用户可添加币种列表
const tokenList = ref([])
const total = ref(0)
const dialogVisible = ref(false)
const input = ref('')
const value = ref('')
const loading = ref(false)
const ruleForm = reactive({
  tokenIds: '',
  chainId: 56, // 初始化为第一个chainId,
  symbol:''
})

// 获取 所有币种列表
async function getAllTokenListFun(id) {
  try {
    loading.value = true
    const chainData = unref(canAddList).filter(item => item.chainId === id)
    resetFormChainId()
    const {code, data, msg} = await getAllTokenList({
      chainName: unref(chainData)[0].chainName,
      chainId: unref(chainData)[0].chainId,
      pageSize: 999,
      pageIndex: 1
    })
    if (code === 200) {
      console.log(data)
      tokenList.value = data.map(item => {
        return {
          ...item,
          isShow: true
        }
      });
      console.log(unref(tokenList))
    }else{
      ElMessage.error(msg)
    }
  }catch (e) {
    console.log(e)
  } finally {
    loading.value = false
  }

}


// 添加币种时用来筛选 symbol
const symbol = ref()

async function handleSymbol() {
  console.log(symbol.value)
  tokenList.value = unref(tokenList).map(item => {
    return {
      ...item,
      isShow: item.symbol.toUpperCase().includes(symbol.value.toUpperCase())
    }
  })
}

// 分页参数
const invoiceData = reactive({
  total: 0,
  pageSize: 10,
  pageNumber: 1,
  tableData: [],
})

// 查询参数
const queryParams = reactive([
  {
    address: '',
    symbol: ''
  }
])

// 获取用户的代币列表
async function getList(address, symbol) {
  try {
    loading.value = true
    const {code, data, msg} = await getUserTokens({
      pageIndex: pageIndex.value,
      pageSize: unref(pageSize),
      address: address ? address : '',
      symbol: symbol ? symbol : ''
    })
    if (code === 200) {
      invoiceData.tableData = data.list
      invoiceData.total = Number(data.total)
      total.value = data.total
    } else {
      ElMessage.error(msg)
    }
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}

// 获取链列表
async function getChainList() {
  const {data} = await getConfigList();
  console.log(data);
  canAddList.value = data;
}

// 点击添加币种按钮
function funAdd() {
  dialogVisible.value = true;
}

// 关闭添加币种 dialog
async function handleClose() {
  ruleForm.chainId = undefined
  symbol.value = undefined
  tokenList.value = undefined
  checkList.value = []
}


// 清空添加币种的数据
function resetCheckList() {
  checkList.value = []
}

// 重选chainId时, 清空 resetForm tokenIds
function resetFormChainId() {
  ruleForm.tokenIds = undefined
}

// 提交添加币种
async function submit() {
  if (checkList.value.length === 0) {
    ElMessage.warning(t('message.AddCurrencyTips2'))
    return
  }
  try {
    loading.value = true
    const {code, msg} = await addToken({tokenIds: checkList.value})
    if (code === 200) {
      ElMessage.success(t('message.AddSuccess'))
    } else {
      ElMessage.error(msg)
    }
  } catch (e) {
    console.log(e)
  } finally {
    loading.value = false
    dialogVisible.value = false;
    resetCheckList()
    await getList()
  }
}

// 多选  start
const checkList = ref([]) // 多选列表
const id = ref()
const handleCheck = (id, checked) => {
  console.log(id, checked)
  if (event.target.checked) {
    checkList.value.push(id);
  } else {
    const index = checkList.value.indexOf(id);
    if (index !== -1) {
      checkList.value.splice(index, 1);
    }
  }
}

// 多选  end

// 打开 dialog 时默认选中 bsc
const resetSelectToFirst = async () => {
  if (canAddList.value.length > 0) {
    ruleForm.chainId = canAddList.value[0].chainId;
  }

  await getAllTokenListFun(ruleForm.chainId)
}

// 搜索方法
const onSubmit = (address, symbol) => {
  // 查询时把 pageIndex 重置为1
  pageIndex.value = 1
  getList(address, symbol);
}

// 清除  queryParams
const onClear = () => {
  // 清除  queryParams
  queryParams.address = ''
  queryParams.symbol = ''
}

// 重置方法
const onReset = () => {
  onClear();
  getList();
}

// 分页
function handleSizeChange(val) {
  pageSize.value = val
  getList()
}

// 分页
function handleCurrentChange(val) {
  pageIndex.value = val
  getList(queryParams.address, queryParams.symbol)
}
</script>


<style scoped lang="less">
.btn {
  text-align: left;
  margin: 10px;
}

// 查询样式
.searchBar {
  :deep(.el-form-item) {
    width: 300px !important;
    margin-right: 20px;
    margin-bottom: 0;
  }
}


// 添加币种样式
.addCurrency {

  .addHeader {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    margin-top:.3rem;

    :deep(.el-select__wrapper) {
      height: 50px;
      line-height: 50px;
    }

    :deep(.el-input) {
      height: 50px;
      line-height: 50px;
    }
  }

  .addBody {

    //border: .5px solid #f0f0f0;
    .body_content:hover {
      cursor: pointer;
    }

    .body_content {
      padding-left: .1rem;
      box-sizing: border-box;
      height: .6rem;
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      align-items: center;
      border-bottom: 1px solid #f3f5fa;

      .body_left {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        align-items: flex-start;

        .currencyName {
          font-size: .15rem;
        }
      }

    }
  }

  .selectAll {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;

    .selectAll_text {
      margin-right: 10px;
    }
  }

}

.scrollable-container {
  /* 当内容溢出时显示滚动条 */
  overflow-y: auto; /* 仅在垂直方向上滚动，如果需要水平滚动，可以使用overflow-x: auto 或 overflow: auto */
  /* 可选：为滚动条设置样式，注意这些样式在Webkit内核的浏览器（如Chrome、Safari）中生效 */
  scrollbar-width: thin; /* Firefox */
  scrollbar-color: rgba(0, 0, 0, 0.2) rgba(255, 255, 255, 0.9); /* Firefox */

  /* 其他样式，如高度、宽度等，根据需要自行设置 */
  height: 200px; /* 限制容器高度以演示滚动效果 */
  //border: 1px solid #ccc;
  padding: 10px;
}

/* Webkit内核浏览器的滚动条样式 */
.scrollable-container::-webkit-scrollbar {
  width: 8px; /* 滚动条宽度 */
}

.scrollable-container::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.9); /* 滚动条轨道颜色 */
}

.scrollable-container::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.2); /* 滚动条拇指颜色 */
  border-radius: 4px; /* 滚动条拇指圆角 */
}


// el-tooltip 样式
.tooltip-base-box {
  width: 600px;
}

.tooltip-base-box .row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.tooltip-base-box .center {
  justify-content: center;
}

.tooltip-base-box .box-item {
  width: 110px;
  margin-top: 10px;
}
</style>